<template>
  <a-drawer
    title="选择班次"
    :visible="visible"
    :width="800"
    :body-style="{
      paddingBottom: '60px',
      height: 'calc(100% - 55px)',
    }"
    @close="onClose"
  >
    <section>
      <a-table
        :dataSource="dataList"
        :columns="columns"
        rowKey="id"
        :pagination="false"
        @change="handleTableChange"
        :row-selection="rowSelection"
        :customRow="customRow"
      >
        <template #title>
          <a-row type="flex" justify="space-between">
            <a-col>
              <a-input-search
                v-model:value="shift_name"
                placeholder="搜索班次名称"
                enter-button
                :allowClear="true"
                @search="getDataList(true)"
              />
            </a-col>
            <a-col>
              <a-button type="primary" @click="addShift()">
                <template #icon>
                  <PlusOutlined />
                </template>
                新建班次
              </a-button>
            </a-col>
          </a-row>
        </template>
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'time_detail'">
            <a-space direction="vertical">
              <div v-for="(item, index) of text" :key="index">
                <span v-if="item.startNextDay">次日</span>
                <span>{{ item.start }}</span>
                ~
                <span v-if="item.endNextDay">次日</span>
                <span>{{ item.end }}</span>
              </div>
            </a-space>
          </template>
        </template>
      </a-table>
    </section>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose">取消</a-button>
        <a-button type="primary" @click.prevent="onConfirm"> 确定 </a-button>
      </a-space>
    </div>
    <add-shift
      :visible="addVisible"
      :id="editId"
      :isCheck="isCheck"
      @cancel="addVisible = false"
      @success="addShiftSuccess"
    />
  </a-drawer>
</template>

<script>
import { defineComponent, watch, computed, reactive, toRefs, toRaw } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import AddShift from "./AddShift.vue";
import { message } from "ant-design-vue";

export default defineComponent({
  name: "ChooseShifts",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    selectedKeys: {
      type: Array,
      default: () => [],
    },
    tableKey: {
      type: Number,
      default: 0,
    },
    // radio 单选 checkbox 多选
    checkType: {
      type: String,
      default: "radio",
    },
    min: {
      type: Number,
      default: 1,
    },
  },
  components: { PlusOutlined, AddShift },
  setup(props, { emit }) {
    const state = reactive({
      columns,
      shift_name: "",
      page: 1,
      pageSize: 10,
      total: 0,
      dataList: [],
      editId: 0,
      isCheck: false,
      addVisible: false,
      selectedRowKeys: [],
      selectedRows: [],
    });
    const addShift = (id, isCheck = false) => {
      state.editId = id || 0;
      state.isCheck = isCheck;
      state.addVisible = true;
    };
    const addShiftSuccess = () => {
      state.addVisible = false;
      getDataList(true);
    };

    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      type: props.checkType,
      onChange: onSelectedRowChange,
    }));
    const onSelectedRowChange = (keys, rows) => {
      state.selectedRowKeys = keys;
      state.selectedRows = rows;
    };

    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };
    const handleTableRowClick = (record) => {
      if (props.checkType == "radio") {
        state.selectedRowKeys = [record.id];
        state.selectedRows = [record];
      } else {
        const index = state.selectedRowKeys.findIndex(
          (item) => item == record.id
        );
        if (index == -1) {
          state.selectedRowKeys.push(record.id);
          state.selectedRows.push(record);
        } else {
          state.selectedRowKeys.splice(index, 1);
          const index2 = state.selectedRows.findIndex(
            (item) => item.id == record.id
          );
          state.selectedRows.splice(index2, 1);
        }
      }
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showTotal: (total) => `共${total}条`,
      showSizeChanger: true,
    }));
    const handleTableChange = (pager, filter, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getDataList();
    };

    const getDataList = (init = false) => {
      state.selectedRows = [];
      request.get("/org", "/shift/list").then((res) => {
        state.dataList = res.list.map((item) => ({
          ...item,
          time_detail: utils.getShiftTimeDetail(item.time_detail),
        }));
        if (state.selectedRowKeys.length) {
          state.selectedRowKeys.forEach((key) => {
            const result = state.dataList.find((item) => item.id == key);
            state.selectedRows.push(result);
          });
        }
      });
    };

    const onConfirm = () => {
      if (!state.selectedRowKeys.length && props.min > 0) {
        message.warning("您还未勾选班次！");
        return;
      }
      emit("success", {
        list: state.selectedRows,
        keys: state.selectedRowKeys,
        tableKey: props.tableKey,
      });
    };

    const init = () => {
      state.selectedRowKeys = props.selectedKeys;
      getDataList(true);
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        }
      }
    );

    const onClose = () => {
      emit("cancel");
    };
    return {
      pagination,
      rowSelection,
      ...toRefs(state),
      onClose,
      onConfirm,
      handleTableChange,
      addShift,
      addShiftSuccess,
      getDataList,
      customRow,
    };
  },
});
const columns = [
  {
    title: "班次名称",
    dataIndex: "shift_name",
    key: "shift_name",
  },
  {
    title: "考勤时间",
    dataIndex: "time_detail",
    key: "time_detail",
  },
];
</script>

<style lang="less" scoped></style>
